
import React, { useState, useEffect } from 'react';
import useStore from '@/store/index'
import { v4 as uuidv4 } from 'uuid';
import { searchVipApi } from '@/api/vip/vip'
import { Button, Card, Space, Form, Input, Select, message, Row, Modal ,Radio} from 'antd';
import { Table } from 'antd';
import { searchPackageApi ,fastCumApi} from '@/api/package/package';
import { searchGoodsApi } from '@/api/goods/goods';
import { searchStaffApi } from '@/api/staff/staff';
const { Search } = Input;




const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 16,
    },
  },
};

const columns: any = [
  {
    title: '姓名',
    dataIndex: 'vipName',
    render: (text: string) => <a>{text}</a>,
  },
  {
    title: '电话',
    dataIndex: 'vipPhone',
  },
  {
    title: '等级',
    dataIndex: 'vipRank',
  },
  {
    title: '余额',
    dataIndex: 'money',
  },
  {
    title: '积分',
    dataIndex: 'score',
  },
];

const packageColumns: any = [
  {
    title: '套餐名',
    dataIndex: 'packageName',
    render: (text: string) => <a>{text}</a>,
  },
  {
    title: '价格',
    dataIndex: 'packagePrice',
  },

];
const staffColumns: any = [

  {
    title: '员工姓名',
    dataIndex: 'staffName',
    render: (text: string) => <a>{text}</a>,
  },

]


export default function FastCsm() {
  const [form] = Form.useForm();
  const [id, setId] = useState('')
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const userInfo = useStore<any>((state: any) => state.userInfo)
  // 会员搜索结果
  const [vipData, setVipData] = useState<any>();
  const [vipCum, setVipCum] = useState<any>();
  // 套餐搜索结果
  const [packageData, setPackageData] = useState<any>();
  const [packageName, setPackageName] = useState<any>();
  // 商品搜索结果
  const [goodsData, setGoodsData] = useState<any>();
  const [goods, setGoods] = useState<any>();
  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');
  // 员工信息
  const [staffData, setStaffData] = useState<any>();
  const [staffName, setStaffName] = useState<any>();
  // 结算
  const [cum, setCum] = useState<any>(0);
  const [cutCum, setCutCum] = useState<any>(0);
  const [getScore, setGetScore] = useState<any>(0);
  const [notes, setNotes] = useState<any>(0);
  const [payWay, setPayWay] = useState<any>('余额');
  
  // 折扣力度
  // const [cut, setCut] = useState<any>(0);
  let cut = 0
  // 选择员工模态框
  const [isModalOpen, setIsModalOpen] = useState(false);
  useEffect(() => {
    setId(uuidv4())
  }, [])
  const onFinish = async (values: any) => {
    if(!id){
      return message.open({
        type: 'error',
        content: '请生成一个id',
      });
    }else if(!vipCum){
      return message.open({
        type: 'error',
        content: '请选择会员',
      });
    }else if(!packageName){
      return message.open({
        type: 'error',
        content: '请选择套餐',
      });
    }else if(!staffName){
      return message.open({
        type: 'error',
        content: '请选择员工',
      });
    }else {
      let params:any = {}
      params.id=id
      params.userId=vipCum.id
      params.userName=vipCum.vipName
      params.packageName=packageName.packageName
      params.packagePrice=packageName.packagePrice
      params.packageNum=1
      params.payWay=payWay
      params.staff = staffName.staffName
      params.totalPrice=cum
      params.cutPrice=cutCum
      params.getScore=getScore
      params.notes=notes
      let res:any = await fastCumApi(params)
      if(res.code ==200){
            // 清空所有数据
            setVipData('')
            setVipCum('')
            setPackageData('')
            setPackageName('')
            setStaffName('')
            setCum(0)
            setCutCum(0)
            setGetScore(0)
            setSelectedRowKeys([])
            // 重新生成id
            setId(uuidv4())
            return message.open({
              type: 'success',
              content: res.msg,
            });
      }else{
        return message.open({
          type: 'error',
          content: res.msg,
        });
      }
    }
    
    
    // 清空所有数据
    // setVipData('')
    // setVipCum('')
    // setPackageData('')
    // setPackageName('')
    // setStaffName('')
    // setCum(0)
    // setCutCum(0)
    // setGetScore(0)
    // setSelectedRowKeys([])
  };
  const searchVip = (value: any) => {
    console.log('关键字', value);
    let params = {
      keyWord: value,
      belongToShop: userInfo.storeId
    }
    if (!value) {
      setVipCum('')
      setSelectedRowKeys([]);
    }
    searchVipApi(params).then(searchRes => {
      if (searchRes.code == 200) {
        let newVip = searchRes.viplist.map((viplist_item) => {
          return {
            "id": viplist_item.id.substring(0, 6),
            'key': viplist_item.id,
            "vipName": viplist_item.vipName,
            "sex": viplist_item.sex,
            "vipPhone": viplist_item.vipPhone,
            "vipRank": viplist_item.vipRank,
            "money": viplist_item.money,
            "score": viplist_item.score,

          }
        })
        setVipData(newVip)

        message.open({
          type: 'success',
          content: searchRes.msg,
        });
      } else {
        setVipData('')
        message.open({
          type: 'error',
          content: searchRes.msg,
        });
      }
    })

  }
  const searchPackage = (value: any) => {
    let params = {
      keyWord: value,
      belongToShop: userInfo.storeId
    }
    if (!vipCum) {
      return message.open({
        type: 'error',
        content: '请先选择用户',
      });
    }
    searchPackageApi(params).then(res => {
      if (res.code == 200) {
        let newPackageList = res.packageList.map(item => {
          return {
            key: item.id,
            id: item.id,
            packageName: item.packageName,
            packagePrice: item.packagePrice
          }
        })

        setPackageData(newPackageList)
        console.log('packageData', packageData);
        message.open({
          type: 'success',
          content: res.msg,
        });
      } else {
        message.open({
          type: 'error',
          content: res.msg,
        });
      }
    })
  }
  const searchGoods = (value: any) => {
    let params = {
      keyWord: value,
      belongToShop: userInfo.storeId
    }
    searchGoodsApi(params).then(res => {
      console.log(res.goodsList);
      if (res.code == 200) {
        let newGoodsList = res.goodsList.map((item: any) => {
          return {
            key: item.id,
            id: item.id,
            goodsName: item.goodsName,
            goodsPrice: item.goodsPrice
          }
        })
        setGoodsData(newGoodsList)
        console.log('setGoodsData', goodsData);
        message.open({
          type: 'success',
          content: res.msg,
        });
      } else {
        message.open({
          type: 'error',
          content: res.msg,
        });
      }
    })
  }
  const rowSelection = {
      onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
        console.log(`选中: ${selectedRowKeys}`, '选中数组: ', selectedRows.length);
        if(selectedRows.length > 1){
          setVipCum(selectedRows[0])

        }else{
          setVipCum(selectedRows[0])
        }
      },
      getCheckboxProps: (record: any) => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };
  const packOnSelectChange =  (newSelectedRowKeys: React.Key[], selectedRows: any) => {
    console.log('pqckage changed: ', newSelectedRowKeys, selectedRows.length);
    if (selectedRows.length == 1) {
      setSelectedRowKeys(newSelectedRowKeys);
      setPackageName(selectedRows[0])
      if (!vipCum) {
                return message.open({
                  type: 'error',
                  content: '请先选择用户1',
                });
        } 
      if (vipCum.vipRank == '黄金会员') {
                  cut = 98 / 100
                  // setCut(98/100)
                } else if (vipCum.vipRank == '铂金会员') {
                  // setCut(95/100)
                  cut = 95 / 100
                } else if (vipCum.vipRank == '砖石会员') {
                  // setCut(90/100)
                  cut = 90 / 100
                }
                setCum(selectedRows[0].packagePrice)
                setCutCum(selectedRows[0].packagePrice * cut)
                setGetScore(selectedRows[0].packagePrice * cut / 10)
    } else if (selectedRows.length > 1) {
      return message.open({
        type: 'error',
        content: '请先取消之前勾选的选项',
      });
    } else if (selectedRows.length == 0) {
      setSelectedRowKeys([]);
      setPackageName('')
    }
  };
 
  const packRowSelection = {
    selectedRowKeys,
    onChange: packOnSelectChange,
  };
const selectPayWay = (e:any)=>{
  console.log(e);
  setPayWay(e.target.value)
}

 
  const goodsRowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
      console.log(`选中: ${selectedRowKeys}`, '选中数组: ', selectedRows);
      if (selectedRows.length == 1) {
        setGoods(selectedRows)

      } else if (selectedRows.length > 1) {
        setGoods(selectedRows)
      } else if (selectedRows.length == 0) {
        setGoods(selectedRows)
      }
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };
  const staffRowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
      console.log(`选中: ${selectedRowKeys}`, '选中数组: ', selectedRows);
      if (selectedRows.length == 1) {
        setStaffName(selectedRows[0])
      } else if (selectedRows.length > 1) {
        setStaffName(selectedRows[0])
      } else if (selectedRows.length == 0) {
        setStaffName(selectedRows[0])
      }
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };

  const createUuid = () => {
    setId(uuidv4())
  }

  // 选择员工
  const handleOk = async () => {
    setIsModalOpen(false);

  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const selectStaff = async () => {
    setIsModalOpen(true);
    let searchParams = { keyWord: '理发部', belongToShop: userInfo.storeId }

    try {
      let searchRes = await searchStaffApi(searchParams)
      if (searchRes.code == 200) {
        let newStaffList = searchRes.staff.map((staff: any) => {
          return {
            id: staff.id,
            key: staff.id,
            staffName: staff.staffName,
            staffSex: staff.staffSex,
            staffPhone: staff.staffPhone,
            staffAge: staff.staffAge,
            position: staff.position,
            department: staff.department,
            belongToShop: userInfo.storeId
          }
        })
        console.log(newStaffList);

        setStaffData(newStaffList)
        console.log(staffData);

        
      } else {
        message.error(searchRes.msg)
      }
    } catch (error) {
      message.error('搜索失败' + error)

    }
  }
  return (
    <div>

      <Space direction="vertical" size={16}>

        <Card size="small" title="会员快速消费" style={{ width: '100%' }}>
          <Form
            form={form}
            name="register"
            onFinish={onFinish}
            initialValues={{ residence: ['zhejiang', 'hangzhou', 'xihu'], prefix: '86' }}
            style={{ width: 600 }}
            scrollToFirstError
          >
            <div>
              <Search
                placeholder="手机号/会员卡号/姓名"
                allowClear
                enterButton="查询"
                style={{ width: 500 }}
                onSearch={searchVip}
              />
              <Button className='vip_btn' type="primary" >
                散客
              </Button>
            </div>
            <div style={{ display: 'flex', justifyContent: "space-between", marginTop: '10px' }}>
              <p>姓名：<span style={{ color: 'red' }}>{vipCum ? vipCum.vipName : 'XXX'}</span></p>
              <p>电话：<span style={{ color: 'red' }}>{vipCum ? vipCum.vipPhone : 'XXX'}</span></p>
              <p>等级：<span style={{ color: 'red' }}>{vipCum ? vipCum.vipRank : 'XXX'}</span></p>
              <p>余额：<span style={{ color: 'red' }}>{vipCum ? vipCum.money : 'XXX'}</span></p>
              <p>积分：<span style={{ color: 'red' }}>{vipCum ? vipCum.score : 'XXX'}</span></p>
            </div>
            <div>
              <Table
                rowSelection={{
                  type: 'radio',
                  ...rowSelection,
                }}
                columns={columns}
                dataSource={vipData}
                pagination={false}
                showHeader={false}
              />
            </div>
            <Row gutter={8}>
              <div>订单编号：</div>
              <Input disabled={true} value={id} />
              <Button block onClick={createUuid}>生成卡号</Button>
            </Row>
            <Row gutter={8}>
              <div>提成员工：</div>

              <Input disabled={true} value={staffName ? staffName.staffName : '请选择员工'} />

              <Button block onClick={selectStaff}>选择员工</Button>
              </Row>
              <div>
                <h2>请选择支付方式</h2>
              <Radio.Group onChange={selectPayWay} value={payWay}>
                <Space direction="vertical">
                  <Radio value={'余额'}>余额</Radio>
                  <Radio value={'微信'}>微信</Radio>
                  <Radio value={'支付宝'}>支付宝</Radio>
                </Space>
              </Radio.Group>
              </div>
            <Row gutter={8}>

              <div>备注：</div>

              <textarea onChange={(e) => setNotes(e.target.value)} name="" id="" value={notes}></textarea>
            </Row>

            <div style={{ display: 'flex', justifyContent: "space-between", marginTop: '30px' }}>
              <div style={{ color: 'red' }}>消费合计：{cum}</div>
              <div style={{ color: 'red' }}>折后金额：{cutCum}</div>
              <div style={{ color: 'red' }}>获得积分：{getScore}</div>
            </div>
            <Form.Item {...tailFormItemLayout}>
              <Button style={{ marginRight: '20px', marginTop: '20px' }} >
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                结算
              </Button>
            </Form.Item>
          </Form>

        </Card>

      </Space>
      <Space direction="vertical" size={16}>
        <Card style={{ width: ' 100%' }} size="small" title="物品消费">
          <div>
            <Search
              placeholder="套餐名称"
              allowClear
              enterButton="查询"
              style={{ width: 500 }}
              onSearch={searchPackage}
            />
          </div>
          <div style={{ display: 'flex', justifyContent: "space-between", marginTop: '10px' }}>
            <p>套餐名称：<span style={{ color: 'red' }}>{packageName ? packageName.packageName : 'XXX'}</span></p>
            <p>套餐价格：<span style={{ color: 'red' }}>{packageName ? packageName.packagePrice + '元' : 'XXX'}</span></p>
          </div>
          <div>
             <Table
                rowSelection={{
                  type: 'radio',
                  ...packRowSelection}}
                columns={packageColumns}
                dataSource={packageData}
                pagination={false}
                showHeader={false}
              />
          </div>
        </Card>
        {/* <Card  style={{ width:' 100%' }}>
                <div>
                    <Search
                        placeholder="商品名称"
                        allowClear
                        enterButton="查询"
                        style={{ width: 500 }}
                        onSearch={searchGoods}
                    />
                </div>
                
                <div style={{display:'flex', justifyContent:"space-between" ,marginTop:'10px'}}>
                    <p>商品名称：<span style={{color:'red'}}>{goods ? goods.goodsName : 'XXX'}</span></p>
                    <p>商品价格：<span style={{color:'red'}}>{goods ? goods.goodsPrice : 'XXX'}</span></p>
                </div>
                <div>
                <Table
                        rowSelection={{
                        type: selectionType,
                        ...goodsRowSelection,
                        }}
                        columns={goodsColumns}
                        dataSource={goodsData}
                        pagination={false}
                        showHeader={false}
                    />
                </div>
                </Card> */}
      </Space>
      <Modal title="选择员工" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Table
          rowSelection={{
            type: selectionType,
            ...staffRowSelection,
          }}
          columns={staffColumns}
          dataSource={staffData}
          pagination={false}
          showHeader={false}
        />
      </Modal>
    </div>
  )
}